import { makePicLocal } from "../utils/filesBox.js"
import delay from "../utils/delay.js"
import { downloadUrl, removeFile } from "../utils/fs.js"
import request from "request"

const handleGetSongs = async (content, room) => {
  try {

    let key = content.split("#")[1] || content.split('＃')[1]
    // console.log(key.split('*'))
    let rule = `'#'拼接歌曲名称，':'拼接歌手名，如：'痒:黄龄'`
    if (!key) {
      room.say(rule)
      return
    }
    let artist = key.split(':')[1] || key.split('：')[1]
    console.log(artist)
    console.log( key.split(':'))
    key = artist ? ( key.replace(artist  ,"")  ): key
    key = key.replace(/:|：/,'')
    console.log(key)
  
    let songInfo = await getSongsByName({key,artist,type:'wy'})

    const result = await handleGetSongsByName({key,artist})     
    if (result.data) {
        console.log(result.data)
        // delay(1000)
        // room.say (result.data.url)
    
    } 

    console.log(songInfo?.data)
    const song =  songInfo?.data[0]
    const songId =  songInfo?.data[0]?.id
    if(!songId) throw('no Song')
    room.say `曲名： ${song.name || key}\n\n分享链接：  https://music.163.com/outchain/player?type=2&id=${songId}&auto=1&height=900\n\n歌手： ${song.artist||'不知道'}\n\n专辑：  ${song.album||'不知道'}`
    // const linkUrl = new UrlLink({
    //   description : 'WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love',
    //   thumbnailUrl: 'https://avatars0.githubusercontent.com/u/25162437?s=200&v=4',
    //   title       : 'song',
    //   url         : `https://music.163.com/#/song?id=${songId}`,
    // })
    // console.log(linkUrl)
  } catch (e) {
    console.log(e)
    room.say `查不到这首歌，去搜搜看吧`
  }
}
// 根据名字搜索歌曲id
const  getSongsByName = ({key,type,artist})=>{
    return new Promise((resolve, reject) => {
      var options = {
          'method': 'get',
          'url':encodeURI( `https://jkyapi.top/API/hqyyid.php?type=${type}&name=${key}&page=1&limit=100`),
          'headers': {
            'Content-Type': 'application/json'
          },
      }
      console.log(options)
      request(options, function (error, response) {
          if (error) resolve(error)
            console.log(response)
          let data = JSON.parse(response.body)
        // console.log('歌手:'+artist)
        let data1 = data?.data?.filter(it=>it.name.indexOf(key)>-1)
        data1 = data1.length ? data1 : data.data
        if(artist){
             data1 = data1?.filter(it=>it.artist.indexOf(artist)>-1)
        }
        data.data = data1

        // console.log(data)
          resolve(data)
        })
    })
}

const getSongsById =({id,type})=>{
    return new Promise((resolve, reject) => {
        var options = {
            'method': 'get',
            'url':encodeURI( `https://jkyapi.top/API/yyjhss.php?type=${type}&id=${id}`),
            'headers': {
              'Content-Type': 'application/json'
            },
        }
        request(options, function (error, response) {
            if (error) resolve(error)
            resolve(JSON.parse(response.body))
          })
      })
} 
// 根据名称搜歌曲逻辑实现
const handleGetSongsByName =  ({key,artist})=>{
    return new Promise(async (resolve,roject)=>{
        try{
            let type = 'wy'
         let songInfo = await getSongsByName({key,artist,type})
         console.log('歌曲信息')
         console.log(songInfo)
       
         if(songInfo.data && songInfo.data.length){
           let it = songInfo.data[0]
            const songBuffer = await getSongsById({id:it.id,type:it.type})
            resolve(songBuffer)
         }


        }catch(e){
            console.log(e)
            console.log('搜索是错误')
        }
    })
}
export default handleGetSongs